
package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.AttrValuePojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.service.team.TeamDataHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SupplierContactErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.pro.listbatch.pojo.dto.AddLabelDTO;
import com.xbongbong.pro.log.pojo.dto.RuleBusinessLogDTO;
import com.xbongbong.pro.suppliercontact.pojo.dto.SupplierContactDeleteBatchDTO;
import com.xbongbong.pro.suppliercontact.pojo.dto.SupplierContactEditAttrUpdateDTO;
import com.xbongbong.pro.suppliercontact.pojo.dto.SupplierContactUpdateBatchDTO;
import com.xbongbong.pro.suppliercontact.pojo.dto.SupplierContactUpdateByBusinessRuleDTO;
import com.xbongbong.pro.suppliercontact.pojo.dto.SupplierContactUpdateDTO;
import com.xbongbong.pro.suppliercontact.pojo.vo.SupplierContactDeleteBatchVO;
import com.xbongbong.pro.suppliercontact.pojo.vo.SupplierContactEditAttrUpdateVO;
import com.xbongbong.saas.analytical.impl.SupplierContactValidateAnalyticalServiceImpl;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.SupplierContactEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.LogHandleHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierContactUserModel;
import com.xbongbong.saas.service.SupplierContactService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 供应商联系人service实现层
 * @author WangJian
 * @date  2019-01-23 20:02
 * @since v1.0
 * @version v1.0
 **/
@Service("SupplierContactService")
public class SupplierContactServiceImpl implements SupplierContactService{

    private static final Logger LOG = LoggerFactory.getLogger(SupplierContactServiceImpl.class);

    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private SupplierContactUserModel supplierContactUserModel;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private EsHelper esHelper;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    @Lazy
    private RuleBusinessLogger ruleBusinessLogger;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private LogHelp logHelp;
    @Resource
    private LogHandleHelp logHandleHelp;
    @Resource
    private SupplierContactValidateAnalyticalServiceImpl supplierContactAnalyticalService;
    @Resource
    private TeamDataHelp teamDataHelp;
    @Resource
    private UserTeamHelp userTeamHelp;


    /**
     * 供应商联系人保存前saas特殊校验
     *
     * @param validateDataDTO saas特殊校验数据入参
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        supplierContactAnalyticalService.beforeSave(validateDataDTO);

    }




    /**
     * 供应商联系人保存后逻辑
     *
     * @param saasFormSaveDTO saas保存数据
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public AfterSavePojo afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        AfterSavePojo afterSavePojo = new AfterSavePojo();
        JSONObject newData = saasFormSaveDTO.getNewData();
        JSONObject oldData = saasFormSaveDTO.getOldData();
        Long supplierId = newData.getLong(SupplierContactEnum.SUPPLIER_ID.getAttr());
        Boolean isNew = saasFormSaveDTO.getIsNew();
        Long newSupplierId = FastJsonHelper.getLongFromFormData(newData, SupplierContactEnum.SUPPLIER_ID.getAttr());
        Long oldSupplierId = FastJsonHelper.getLongFromFormData(oldData, SupplierContactEnum.SUPPLIER_ID.getAttr());
        if (!isNew) {
//            if (!Objects.equals(newSupplierId, oldSupplierId)) {
                // 关联供应商改变，删除原联系人协同团队
//                supplierContactUserModel.deleteBatchBySupplierAndContact(oldSupplierId, saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getCorpid());
//                // 建立联系人协同团队
//                userTeamService.createSupplierContactUser(saasFormSaveDTO.getCorpid(),supplierId,Collections.singletonList(saasFormSaveDTO.getNewPaasFormDataEntity().getId()));
            afterSavePojo = teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getNewPaasFormDataEntity(), saasFormSaveDTO.getIsImport(), false);
//            }
        } else {
            // 建立联系人协同团队
            afterSavePojo = teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(),saasFormSaveDTO.getNewPaasFormDataEntity().getId(),saasFormSaveDTO.getNewPaasFormDataEntity(),saasFormSaveDTO.getIsImport(), false);
            //userTeamService.createSupplierContactUser(saasFormSaveDTO.getCorpid(),supplierId,Collections.singletonList(saasFormSaveDTO.getNewPaasFormDataEntity().getId()));
        }
        return afterSavePojo;
    }

    @Override
    public SupplierContactDeleteBatchVO deleteBatch(SupplierContactDeleteBatchDTO supplierContactDeleteBatchDTO) throws XbbException {
        SupplierContactDeleteBatchVO supplierContactDeleteBatchVO = new SupplierContactDeleteBatchVO();
        try {
            List<Long> idIn = supplierContactDeleteBatchDTO.getSupplierContactIdIn();

            //查询编号
            List<String> name= new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            BoolQueryBuilder builder = boolQuery();
            // 添加corpid,formId,del
            builder.filter(termQuery("corpid.keyword", supplierContactDeleteBatchDTO.getCorpid()));
            builder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            builder.filter(termsQuery(StringConstant.DATA_ID, idIn));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            fieldList.add(StringConstant.JSON_DATA);
            List<PaasFormDataEntityExt> noList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT, builder, PaasFormDataEntityExt.class, fieldList);
            PaasFormDataEntityExt formData;
            for(PaasFormDataEntityExt entityExt : noList){
                JSONObject data = entityExt.getData();
                formData = saasUpdateHelp.getFormData(entityExt.getDataId(), supplierContactDeleteBatchDTO.getCorpid(),XbbRefTypeEnum.SUPPLIER_CONTACT.getCode() );
                if (formData ==null ){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                if ( FlowStatusEnum.inApproval(formData.getFlowStatus()) ) {
                    throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200020);
                }
                String sheetName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.NAME.getAttr(), "");
                name.add(sheetName);
            }

            String corpid = supplierContactDeleteBatchDTO.getCorpid();
            if(Objects.nonNull(idIn) && !idIn.isEmpty()) {
                if(BasicConstant.ONE.equals(supplierContactDeleteBatchDTO.getSingleFlag())
                        && BasicConstant.ONE.equals(idIn.size())){
                    supplierContactModel.deleteByKey(idIn.get(0),corpid);
                }else {
                    supplierContactModel.deleteBatch(idIn, corpid);
                }
                supplierContactDeleteBatchVO.setDeleteIds(idIn);
            }
            OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
            if (Objects.equals(1, supplierContactDeleteBatchDTO.getIsBusinessRule())) {
                operateTypeEnum = OperateTypeEnum.RULE_DELETE;
            }
            //生成删除日志(区分单个删除和批量删除)
            String userId = supplierContactDeleteBatchDTO.getUserId();
            String userName = supplierContactDeleteBatchDTO.getLoginUserName();
            String nameStr = StringUtils.join(name, "，");
            if(idIn.size() > 1){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.SUPPLIER_CONTACT.getName(), idIn.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(SupplierContactEnum.NAME.getAttrName());
                infoArrPojo.setContent(nameStr);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER_CONTACT, operateTypeEnum,
                        "", "", memo, supplierContactDeleteBatchDTO.getHttpHeader());
            } else if (Objects.equals(idIn.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.SUPPLIER_CONTACT.getName(), nameStr);
                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER_CONTACT, operateTypeEnum,
                        idIn.get(0).toString(), nameStr, memo, supplierContactDeleteBatchDTO.getHttpHeader());
            }
        } catch (XbbException e){
            throw e;
        }catch (Exception e) {
            LOG.error("supplierContactServiceImpl.deleteBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return supplierContactDeleteBatchVO;
    }

    /**
     * 新建时格式化解释
     *
     * @param handlerExplainInLinkItemDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
        Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId();
        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
        FieldAttrEntity linkSupplierField = new FieldAttrEntity();
        for(FieldAttrEntity fieldAttrEntity :explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), SupplierContactEnum.SUPPLIER_ID.getAttr())) {
                linkSupplierField = fieldAttrEntity;
            }
        }
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
        switch (redundantTemplateTypeEnum) {
            case SUPPLIER:
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, supplierName));
                break;
            default:
                break;
        }
    }

    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
            String attr = fieldAttrEntityForImport.getAttr();
            Integer fieldType = fieldAttrEntityForImport.getFieldType();
            String attrName = fieldAttrEntityForImport.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);

            if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttrEntityForImport, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldType)) {
                    importHelper.formatCommonField(dataJson, fieldAttrEntityForImport, cellValue);
                } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                    formDataAddDTO.setSerialNo(cellValue.toString());
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                    importHelper.formatLinkData(cellValue, fieldAttrEntityForImport, dataJson);
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                    importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttrEntityForImport, dataJson);
                } else {
                    dataJson.put(attr, cellValue);
                }
            }
        }
        if (formDataAddDTO.getSerialNo() == null) {
            formDataAddDTO.setSerialNo("");
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    public void getFormatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result,SupplierContactEnum.SUPPLIER_ID.getAttr(),SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), SupplierContactEnum.SUPPLIER_ID.getFieldType());
    }

    @Override
    public SupplierContactEditAttrUpdateVO batchEditAttr(SupplierContactEditAttrUpdateDTO supplierContactEditAttrUpdateDTO) throws XbbException{
        SupplierContactEditAttrUpdateVO supplierContactEditAttrUpdateVO = new SupplierContactEditAttrUpdateVO();
        try {
            String corpid = supplierContactEditAttrUpdateDTO.getCorpid();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", supplierContactEditAttrUpdateDTO.getDataIdList());
            param.put("del", 0);
            List<SupplierContactEntityExt> supplierContactList  = supplierContactModel.findEntitys(param);
            if (Objects.isNull(supplierContactList)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            //权限团队校验前置了
            List<Long> errorIdList = new ArrayList<>();
//            List<Long> errorIdList = userTeamHelp.batchTeamMembersCheckEditPermission(supplierContactEditAttrUpdateDTO.getBusinessType(), supplierContactEditAttrUpdateDTO.getSaasMark(),
//                    supplierContactEditAttrUpdateDTO.getMenuId(), supplierContactEditAttrUpdateDTO.getLoginUser(), supplierContactEditAttrUpdateDTO.getDistributorMark(),
//                    supplierContactEditAttrUpdateDTO.getDataIdList(), new HashMap<>());
            List<String> errorNameList = new ArrayList<>();
            for (SupplierContactEntityExt supplierContactEntityExt : supplierContactList) {
                if (errorIdList.contains(supplierContactEntityExt.getId())) {
                    errorNameList.add(supplierContactEntityExt.getData().getString(SupplierContactEnum.NAME.getAttr()));
                }
            }
            String nameStr = org.apache.commons.lang.StringUtils.join(errorNameList, "、");
            if (CollectionUtils.isNotEmpty(errorNameList)) {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_271038.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271038.getMsg(), nameStr));
            }
            List<Long> idIn = supplierContactEditAttrUpdateDTO.getDataIdList();
            List<SupplierContactUpdateDTO> supplierContactUpdateDTOS = new ArrayList<>();
            idIn.forEach((item)->{
                SupplierContactUpdateDTO supplierContactUpdateDTO = new SupplierContactUpdateDTO();
                supplierContactUpdateDTO.setId(item);
                JSONObject data = ProSaveHelp.getBatchUpdateData(supplierContactEditAttrUpdateDTO.getFieldEditedList());
                supplierContactUpdateDTO.setData(data);
                supplierContactUpdateDTOS.add(supplierContactUpdateDTO);
            });
            if (!supplierContactUpdateDTOS.isEmpty()) {
                SupplierContactUpdateBatchDTO supplierContactUpdateBatchDTO = new SupplierContactUpdateBatchDTO();
                BeanUtil.copyProperties(supplierContactEditAttrUpdateDTO, supplierContactUpdateBatchDTO);
                supplierContactUpdateBatchDTO.setSupplierContactList(supplierContactUpdateDTOS);
                updateBatch(supplierContactUpdateBatchDTO);
            }

            // 批量编辑日志
            List<String> updataItemList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> dataIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (SupplierContactEntityExt item : supplierContactList) {
                dataIdList.add(item.getId());
                JSONObject data = item.getData();
                String opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.NAME.getAttr(), "");
                updataItemList.add(opObjectName);
            }
            String updataItem = StringUtils.join(updataItemList, "，");
            String userId = supplierContactEditAttrUpdateDTO.getUserId();
            String loginUserName = supplierContactEditAttrUpdateDTO.getLoginUserName();
            // 标签特殊处理
            Integer fieldType = supplierContactEditAttrUpdateDTO.getFieldType();
            Boolean isFieldDependence = supplierContactEditAttrUpdateDTO.getIsFieldDependence();
            logHelp.analysisLabel(corpid, fieldType, isFieldDependence,supplierContactEditAttrUpdateDTO.getLogFieldEditedList());

            String changedLogItemsStr = logHandleHelp.getChangedLogItemsStr(supplierContactEditAttrUpdateDTO.getLogFieldEditedList());
            if(dataIdList.size() > 1 ){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, XbbRefTypeEnum.SUPPLIER_CONTACT.getName(),
                        changedLogItemsStr, dataIdList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(XbbRefTypeEnum.SUPPLIER_CONTACT.getName());
                infoArrPojo.setContent(updataItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.SUPPLIER_CONTACT, OperateTypeEnum.EDIT,
                        "", "", memo, supplierContactEditAttrUpdateDTO.getHttpHeader());
            } else if (Objects.equals(dataIdList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_ATTR), loginUserName, XbbRefTypeEnum.SUPPLIER_CONTACT.getName(), updataItem,
                        changedLogItemsStr);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.SUPPLIER_CONTACT, OperateTypeEnum.EDIT,
                        dataIdList.get(0).toString(), updataItem, memo, supplierContactEditAttrUpdateDTO.getHttpHeader());
            }

        }catch (XbbException e) {
            throw e;
        }  catch (Exception e) {
            LOG.error("supplierContactServiceImpl.batchEditAttr 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return supplierContactEditAttrUpdateVO;
    }

    @Override
    public void dataConsistencyUpdateSupplier(String corpid, Long dataId, String name) throws XbbException {
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termQuery("data." + SupplierContactEnum.SUPPLIER_ID.getAttr() + ".keyword", dataId));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            List<SupplierContactEntityExt> supplierContactList = supplierContactModel.findEntitys(param);

            if (Objects.nonNull(supplierContactList) && !supplierContactList.isEmpty()) {
                List<SupplierContactUpdateDTO> purchaseUpdateDTOList = new ArrayList<>();
                for (SupplierContactEntityExt entityExt : supplierContactList) {
                    SupplierContactUpdateDTO supplierContactUpdateDTO = new SupplierContactUpdateDTO();
                    supplierContactUpdateDTO.setId(entityExt.getId());
                    JSONObject data = new JSONObject();
                    data.put(SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), name);
                    supplierContactUpdateDTO.setData(data);
                    purchaseUpdateDTOList.add(supplierContactUpdateDTO);
                }
                SupplierContactUpdateBatchDTO supplierContactUpdateBatchDTO = new SupplierContactUpdateBatchDTO();
                supplierContactUpdateBatchDTO.setCorpid(corpid);
                supplierContactUpdateBatchDTO.setSupplierContactList(purchaseUpdateDTOList);
                updateBatch(supplierContactUpdateBatchDTO);
            }

        } catch (Exception e) {
            LOG.error("supplierContactServiceImpl.dataConsistencyUpdateSupplier 出错， corpid=" + corpid + "  contactId=" + dataId + "  contactName=" + name, e);
        }
    }


    @Override
    public void updateBatchByBusinessRule(SupplierContactUpdateByBusinessRuleDTO supplierContactUpdateByBusinessRuleDTO) throws XbbException {
        try {
            String corpid = supplierContactUpdateByBusinessRuleDTO.getCorpid();
            List<PaasFormDataEntityExt> formDataList = supplierContactUpdateByBusinessRuleDTO.getFormDataList();
            List<UpdateDataEntity> updateList = ExplainUtil.getUpdateValueByBusinessRule(formDataList, corpid, supplierContactUpdateByBusinessRuleDTO.getOperations());

            if (!updateList.isEmpty()) {
                supplierContactModel.updateBatch(updateList, corpid);

                RuleBusinessLogDTO businessLogDTO = new RuleBusinessLogDTO();
                BeanUtil.copyProperties(supplierContactUpdateByBusinessRuleDTO, businessLogDTO);
                businessLogDTO.setFormDataList(formDataList);
                ruleBusinessLogger.writeLog(businessLogDTO, updateList);
            }
        } catch (Exception e) {
            LOG.error("supplierContactService.updateFormDataByBusinessRule根据业务规则更新数据出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void updateBatchLabelAttr(AddLabelDTO addLabelDTO, List<PaasFormDataEntityExt> addBatchList, Boolean addOrDelete) throws XbbException {
        SupplierContactUpdateBatchDTO supplierContactUpdateBatchDTO = new SupplierContactUpdateBatchDTO();
        BeanUtil.copyProperties(addLabelDTO, supplierContactUpdateBatchDTO);
        List<SupplierContactUpdateDTO> supplierContactList = new ArrayList<>();
        addBatchList.forEach(item->{
            SupplierContactUpdateDTO supplierContactUpdateDTO = new SupplierContactUpdateDTO();
            supplierContactUpdateDTO.setData(item.getData());
            supplierContactUpdateDTO.setId(item.getId());
            supplierContactList.add(supplierContactUpdateDTO);
        });
        supplierContactUpdateBatchDTO.setSupplierContactList(supplierContactList);
        updateBatch(supplierContactUpdateBatchDTO);

    }

    @Override
    public void afterSaveForWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        JSONObject newData = saasFormSaveDTO.getNewData();
        Long supplierId = newData.getLong(SupplierContactEnum.SUPPLIER_ID.getAttr());
        // 建立联系人协同团队
        teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getNewPaasFormDataEntity(), saasFormSaveDTO.getIsImport(), true);
//        userTeamService.createSupplierContactUser(saasFormSaveDTO.getCorpid(),supplierId,Collections.singletonList(saasFormSaveDTO.getNewPaasFormDataEntity().getId()));
    }

    @Override
    public void afterSaveForUpdateWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        JSONObject newData = saasFormSaveDTO.getNewData();
        JSONObject oldData = saasFormSaveDTO.getOldData();
        Long supplierId = newData.getLong(SupplierContactEnum.SUPPLIER_ID.getAttr());
        Long newSupplierId = FastJsonHelper.getLongFromFormData(newData, SupplierContactEnum.SUPPLIER_ID.getAttr());
        Long oldSupplierId = FastJsonHelper.getLongFromFormData(oldData, SupplierContactEnum.SUPPLIER_ID.getAttr());
//        if (!Objects.equals(newSupplierId, oldSupplierId)) {
            // 关联供应商改变，删除原联系人协同团队
//            supplierContactUserModel.deleteBatchBySupplierAndContact(oldSupplierId, saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getCorpid());
//            // 建立联系人协同团队
//            userTeamService.createSupplierContactUser(saasFormSaveDTO.getCorpid(),supplierId,Collections.singletonList(saasFormSaveDTO.getNewPaasFormDataEntity().getId()));
            //新逻辑的团队保存
            teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), newPaasFormDataEntity.getId(), newPaasFormDataEntity,saasFormSaveDTO.getIsImport(),true);
//        }

    }

    private void updateBatch(SupplierContactUpdateBatchDTO supplierContactUpdateBatchDTO) throws XbbException{
        try {
            String corpid = supplierContactUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<SupplierContactUpdateDTO> supplierContactUpdateDTOS = supplierContactUpdateBatchDTO.getSupplierContactList();
            if (Objects.nonNull(supplierContactUpdateDTOS) && !supplierContactUpdateDTOS.isEmpty()) {
                supplierContactUpdateDTOS.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            if (!updateList.isEmpty()) {
                supplierContactModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error("supplierContactServiceImpl.updateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }





    /**
     * 校验供应商联系电话是否存在或是否格式正确
     *
     * @param data 数据源
     * @throws XbbException 如电话为空或者格式不正确是抛出异常
     * @author Jian.Wang
     * @date 2019/1/31 15:19
     * @since v1.0
     **/
    private void checkContactNumber(JSONObject data) throws XbbException {
        JSONArray phoneJsonArray = FastJsonHelper.getJsonArrFromFormData(data, SupplierContactEnum.PHONE.getAttr());
        String phoneNumber = "";
        for (Object object : phoneJsonArray) {
            JSONObject phoneJsonObject = (JSONObject) object;
            phoneNumber = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
        }
        if (StringUtil.isEmpty(phoneNumber)) {
            throw new XbbException(SupplierContactErrorCodeEnum.API_ERROR_252005);
        } /*else if (!StringUtil.isMobile(phoneNumber) || !StringUtil.isPhone(phoneNumber)) {
            throw new XbbException(ErrorCodeEnum.API_ERROR_252006);
        }*/
    }

}
